<template>
  <div class="talent-search-page" :key="animationKey">
    <!-- 顶部导航栏 -->
    <header class="page-header">
      <div class="header-container">
        <div class="logo-section">
          <div class="logo-icon">
            <img :src="logoImage" alt="Logo" class="logo-image" />
          </div>
          <h1 class="logo-title" @click="goToHome">{{ $t('enterpriseTalentSearch.pageTitle') }}</h1>
        </div>
        <nav class="navigation">
          <a href="#" class="nav-link" @click="goToApplications">{{ $t('enterpriseTalentSearch.applications') }}</a>
          <a href="#" class="nav-link" @click="goToHome">{{ $t('enterpriseTalentSearch.home') }}</a>
          <a href="#" class="nav-link active">{{ $t('enterpriseTalentSearch.talentPool') }}</a>
        </nav>
        <div class="right-section">
          <a href="#" class="nav-link" @click="goToEnterpriseSpace">{{ $t('enterpriseTalentSearch.enterpriseSpace') }}</a>

          <div class="nav-icons">
            <div class="icon-item">
              <el-icon size="18" @click="goToNotifications"><Bell /></el-icon>
            </div>
            <div class="icon-item">
              <el-icon size="18"><User /></el-icon>
            </div>
          </div>
        </div>
      </div>
    </header>

    <!-- 搜索和筛选区域 -->
    <section class="search-section">
      <div class="search-container">
        <!-- 搜索栏 -->
        <div class="search-bar">
          <el-input 
            v-model="searchQuery" 
              :placeholder="$t('enterpriseTalentSearch.searchPlaceholder')" 
            class="search-input"
            size="large"
            @keyup.enter="search"
          />
          <el-button type="primary" size="large" @click="search" class="search-btn">
              {{ $t('enterpriseTalentSearch.search') }}
          </el-button>
        </div>


        <!-- 筛选器 -->
        <div class="filter-section">
          <div class="filter-container">
            <!-- 始终显示的前2个筛选条件 -->
            <!-- 留学生国籍筛选（单选） -->
            <div class="filter-row" data-filter-type="nationality">
              <div class="filter-label">{{ $t('enterpriseTalentSearch.nationality') }}</div>
              <div class="filter-tags single-choice">
                <span 
                  class="filter-tag" 
                  :class="{ active: selectedFilters.nationality.length === 0 }"
                    @click="selectFilter('nationality', $t('enterpriseTalentSearch.all'))"
                  style="cursor: pointer;"
                >
                    {{ $t('enterpriseTalentSearch.all') }}
                </span>
                <!-- 显示前15个国家 -->
                <span 
                  v-for="nationality in (filterOptions.nationalities || []).slice(0, 15)" 
                  :key="nationality"
                  class="filter-tag" 
                  :class="{ active: selectedFilters.nationality.includes(nationality) }"
                  @click="selectFilter('nationality', nationality)"
                  style="cursor: pointer;"
                >
                  {{ nationality }}
                </span>
                <!-- 如果有更多国家，显示"其他"选项 -->
                <span 
                  v-if="(filterOptions.nationalities || []).length > 15"
                  class="filter-tag" 
                  @click="showMoreNationalities"
                  style="cursor: pointer;"
                >
                  {{ $t('enterpriseTalentSearch.other') }} ({{ Math.max(0, (filterOptions.nationalities || []).length - 15) }})
                </span>
              </div>
            </div>

            <!-- 专业筛选（多选） -->
            <div class="filter-row" data-filter-type="major">
              <div class="filter-label">{{ $t('enterpriseTalentSearch.major') }}</div>
              <div class="filter-tags multi-choice">
                <span 
                  class="filter-tag" 
                  :class="{ active: selectedFilters.major.length === 0 }"
                    @click="selectFilter('major', $t('enterpriseTalentSearch.all'))"
                  style="cursor: pointer;"
                >
                    {{ $t('enterpriseTalentSearch.all') }}
                </span>
                <span 
                  v-for="major in filterOptions.majors" 
                  :key="major"
                  class="filter-tag" 
                  :class="{ active: selectedFilters.major.includes(major) }"
                  @click="selectFilter('major', major)"
                  style="cursor: pointer;"
                >
                  {{ major }}
                </span>
              </div>
            </div>

            <!-- 可展开的筛选条件 -->
            <transition name="filter-expand">
              <div class="expandable-filters" v-show="showMoreFilters">
                <!-- 学历筛选（单选） -->
                <div class="filter-row" data-filter-type="education">
                  <div class="filter-label">{{ $t('enterpriseTalentSearch.education') }}</div>
                  <div class="filter-tags single-choice">
                    <span 
                      class="filter-tag" 
                      :class="{ active: selectedFilters.education.length === 0 }"
                        @click="selectFilter('education', $t('enterpriseTalentSearch.all'))"
                      style="cursor: pointer;"
                    >
                        {{ $t('enterpriseTalentSearch.all') }}
                    </span>
                    <span 
                      v-for="degree in filterOptions.degrees" 
                      :key="degree"
                      class="filter-tag" 
                      :class="{ active: selectedFilters.education.includes(degree) }"
                      @click="selectFilter('education', degree)"
                      style="cursor: pointer;"
                    >
                      {{ degree }}
                    </span>
                  </div>
                </div>

                <!-- 语言筛选（多选） -->
                <div class="filter-row" data-filter-type="language">
                                      <div class="filter-label">{{ $t('enterpriseTalentSearch.language') }}</div>
                  <div class="filter-tags multi-choice">
                    <span 
                      class="filter-tag" 
                      :class="{ active: selectedFilters.language.length === 0 }"
                        @click="selectFilter('language', $t('enterpriseTalentSearch.all'))"
                      style="cursor: pointer;"
                    >
                        {{ $t('enterpriseTalentSearch.all') }}
                    </span>
                    <span 
                      v-for="language in filterOptions.languages" 
                      :key="language"
                      class="filter-tag" 
                      :class="{ active: selectedFilters.language.includes(language) }"
                      @click="selectFilter('language', language)"
                      style="cursor: pointer;"
                    >
                      {{ language }}
                    </span>
                  </div>
                </div>

                <!-- 技能筛选（多选） -->
                <div class="filter-row" data-filter-type="skill">
                                      <div class="filter-label">{{ $t('enterpriseTalentSearch.skill') }}</div>
                  <div class="filter-tags multi-choice">
                    <span 
                      class="filter-tag" 
                      :class="{ active: selectedFilters.skill.length === 0 }"
                        @click="selectFilter('skill', $t('enterpriseTalentSearch.all'))"
                      style="cursor: pointer;"
                    >
                        {{ $t('enterpriseTalentSearch.all') }}
                    </span>
                    <span 
                      v-for="skill in filterOptions.skills" 
                      :key="skill"
                      class="filter-tag" 
                      :class="{ active: selectedFilters.skill.includes(skill) }"
                      @click="selectFilter('skill', skill)"
                      style="cursor: pointer;"
                    >
                      {{ skill }}
                    </span>
                  </div>
                </div>
              </div>
            </transition>

            <!-- 显示更多按钮 - 始终在最下面 -->
            <div class="show-more-filters">
              <span class="show-more-btn" @click="toggleMoreFilters">
                <span>{{ showMoreFilters ? $t('enterpriseTalentSearch.hideFilters') : $t('enterpriseTalentSearch.showMoreFilters') }}</span>
                <el-icon class="arrow-icon" :class="{ 'rotated': showMoreFilters }">
                  <ArrowDown />
                </el-icon>
              </span>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- 人才卡片网格 -->
    <section class="talents-section">
      <div class="talents-container" v-loading="loading">
        <!-- 结果统计 -->
        <div v-if="!loading" class="result-stats">
          <p>{{ $t('enterpriseTalentSearch.foundTalents', { count: totalCount }) }}</p>
        </div>
        
        <!-- 人才列表 -->
        <div v-if="!loading" class="talents-grid">
          <div class="talent-card" v-for="talent in talents" :key="talent.studentId">
            <div class="talent-header">
              <div class="talent-info">
                <div class="talent-name-row">
                  <h3 class="talent-name">{{ talent.fullName }}</h3>
                  <el-tag 
                    v-if="talent.hasApplied" 
                    size="small" 
                    type="success"
                    class="status-tag"
                  >
                    {{ talent.statusDisplay || $t('enterpriseTalentSearch.applied') }}
                  </el-tag>
                </div>
                <p class="talent-nationality">{{ talent.nationality }}</p>
                <p class="talent-education" v-if="talent.education && talent.education.length > 0">
                  {{ talent.education[0].major }} | {{ talent.education[0].degree }}
                </p>
              </div>
            </div>
            
            <div class="talent-details">
              <div class="detail-item" v-if="talent.languages && talent.languages.length > 0">
                <span class="detail-label">语言:</span>
                <span class="detail-value">{{ talent.languages.join(', ') }}</span>
              </div>
              <div class="detail-item" v-if="talent.skills && talent.skills.length > 0">
                <span class="detail-label">技能:</span>
                <span class="detail-value">{{ talent.skills.join(', ') }}</span>
              </div>

            </div>
            
            <div class="talent-actions">
              <el-button type="info" size="small" @click="viewTalentDetail(talent)">
                {{ $t('enterpriseTalentSearch.viewDetails') }}
              </el-button>
              <el-button 
                :type="talent.hasApplied ? 'info' : 'primary'" 
                size="small" 
                :disabled="talent.hasApplied"
                @click="requestMatch(talent)"
              >
                {{ talent.hasApplied ? $t('enterpriseTalentSearch.alreadyApplied') : $t('enterpriseTalentSearch.requestMatch') }}
              </el-button>
            </div>
          </div>
        </div>
        
        <!-- 空状态 -->
        <div v-if="!loading && talents.length === 0" class="empty-state">
          <p>{{ $t('enterpriseTalentSearch.noData') }}</p>
        </div>
        
        <!-- 分页组件 -->
        <div v-if="!loading && totalPages > 1" class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="totalCount"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
          />
        </div>
      </div>
    </section>

    <!-- 人才详情弹窗 -->
    <el-dialog 
      v-model="talentDetailVisible" 
      width="800px"
      :before-close="() => talentDetailVisible = false"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      top="5vh"
      :append-to-body="true"
    >
      <div v-if="currentTalentDetail" class="talent-detail-content">
        <!-- 姓名标题 -->
        <div class="resume-header">
          <h2 class="resume-name">{{ currentTalentDetail.fullName }}</h2>
        </div>

        <!-- 基本信息 - 居中显示，用"|"分隔 -->
        <div class="basic-info-section">
          <div class="basic-info-line">
            <span v-if="currentTalentDetail.gender">{{ currentTalentDetail.gender === 'male' ? '男' : '女' }}</span>
            <span v-if="currentTalentDetail.nationality">{{ currentTalentDetail.nationality }}</span>
            <span v-if="currentTalentDetail.dateOfBirth">{{ formatDate(currentTalentDetail.dateOfBirth) }}</span>
            <span v-if="currentTalentDetail.studentId">{{ currentTalentDetail.studentId }}</span>
            <span v-if="currentTalentDetail.email">{{ currentTalentDetail.email }}</span>
          </div>
          <div class="basic-info-line">
            <span>求职意向：{{ currentTalentDetail.jobIntention || '暂未设定' }}</span>
            <span>期望薪资：{{ currentTalentDetail.expectedSalary || '面议' }}</span>
          </div>
        </div>

        <!-- 教育背景 -->
        <div class="resume-section" v-if="currentTalentDetail.education && currentTalentDetail.education.length > 0">
          <h3 class="section-title">教育背景</h3>
          <div class="section-content">
            <div class="education-item">
              <div class="education-info">
                <span class="education-degree">{{ currentTalentDetail.education[0].degree }}：</span>
                <span class="education-major">{{ currentTalentDetail.education[0].major }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 语言能力 -->
        <div class="resume-section" v-if="currentTalentDetail.languages && currentTalentDetail.languages.length > 0">
          <h3 class="section-title">语言能力</h3>
          <div class="section-content">
            <div class="text-content">
              {{ currentTalentDetail.languages.join('、') }}
            </div>
          </div>
        </div>

        <!-- 技能特长 -->
        <div class="resume-section" v-if="currentTalentDetail.skills && currentTalentDetail.skills.length > 0">
          <h3 class="section-title">技能特长</h3>
          <div class="section-content">
            <div class="text-content">
              {{ currentTalentDetail.skills.join('、') }}
            </div>
          </div>
        </div>

        <!-- 经验内容 -->
        <div class="resume-section" v-if="currentTalentDetail.resumeContent">
          <h3 class="section-title">经验</h3>
          <div class="section-content">
            <div class="resume-content" v-html="currentTalentDetail.resumeContent">
            </div>
          </div>
        </div>

        <!-- 简历状态 -->
        <div class="resume-section">
                      <h3 class="section-title">{{ $t('enterpriseTalentSearch.resumeStatus') }}</h3>
          <div class="section-content">
            <div class="resume-status">
              <el-tag :type="getResumeStatusType(currentTalentDetail.resumeStatus)">
                {{ getResumeStatusText(currentTalentDetail.resumeStatus) }}
              </el-tag>
              <span class="update-time">更新时间：{{ formatDate(currentTalentDetail.updatedAt) || 'N/A' }}</span>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="talentDetailVisible = false">关闭</el-button>
          <el-button 
            :type="currentTalentDetail?.hasApplied ? 'info' : 'primary'"
            :disabled="currentTalentDetail?.hasApplied"
            @click="requestMatch(currentTalentDetail)"
          >
            {{ currentTalentDetail?.hasApplied ? '已申请撮合' : '申请撮合' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 其他国家选择弹窗 -->
    <el-dialog 
      v-model="moreNationalitiesVisible" 
              :title="$t('enterpriseTalentSearch.showMoreNationalities')" 
      width="600px"
      :before-close="() => moreNationalitiesVisible = false"
    >
      <div class="more-nationalities-content">
        <div class="nationalities-grid">
          <span 
            v-for="nationality in (filterOptions.nationalities || []).slice(15)" 
            :key="nationality"
            class="nationality-item" 
            @click="selectFromMoreNationalities(nationality)"
          >
            {{ nationality }}
          </span>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="moreNationalitiesVisible = false">{{ $t('common.cancel') }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { User, Bell, ArrowDown } from '@element-plus/icons-vue'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import logoImage from '../../assets/images/login/logo2.png'
import { talentApi } from '@/api'

const router = useRouter()

// 国际化
const { t, locale } = useI18n()

// 强制重新渲染的key
const animationKey = ref(0)

// 搜索和筛选数据
const searchQuery = ref('')
const selectedFilters = ref({
  nationality: [],
  major: [],
  education: [],
  language: [],
  skill: []
})

// 人才数据
const talents = ref([])
const totalCount = ref(0)
const loading = ref(false)

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const totalPages = ref(0)
const hasNext = ref(false)
const hasPrevious = ref(false)

// 筛选选项数据
const filterOptions = ref({
  nationalities: [],
  majors: [],
  degrees: [],
  languages: [],
  skills: []
})

// 人才详情弹窗数据
const talentDetailVisible = ref(false)
const currentTalentDetail = ref(null)

// 其他国家选择弹窗数据
const moreNationalitiesVisible = ref(false)

// 控制更多筛选条件展开/收起
const showMoreFilters = ref(false)

// 计算属性
const hasSelectedFilters = computed(() => {
  return Object.values(selectedFilters.value).some(filters => filters.length > 0)
})

// 筛选类型说明
// 单选类型：国籍、学历 - 只能选择一个选项
// 多选类型：专业、语言、技能 - 可以选择多个选项

// 导航方法
const goToHome = () => {
  router.push({ name: 'enterprise-home' })
}

const goToApplications = () => {
  router.push({ name: 'applications-list' })
}



const goToEnterpriseSpace = () => {
  router.push({ name: 'enterprise-space' })
}

const goToNotifications = () => {
  router.push('/code/enterprise/notifications')
}

// 检查已申请状态
const checkAppliedStatus = async () => {
  try {
    // 这里可以调用后端接口获取已申请的人才列表
    // 暂时使用本地存储模拟，实际项目中应该调用API
    const appliedTalents = JSON.parse(localStorage.getItem('appliedTalents') || '[]')
    
    // 更新人才列表中的申请状态
    talents.value.forEach(talent => {
      const appliedTalent = appliedTalents.find(applied => applied.studentId === talent.studentId)
      if (appliedTalent) {
        talent.hasApplied = true
        talent.requestStatus = appliedTalent.status || 'submitted'
        talent.statusDisplay = appliedTalent.statusDisplay || '已申请'
      }
    })
  } catch (error) {
    console.error('检查申请状态失败:', error)
  }
}

// 语言初始化
const initLanguage = () => {
  const savedLang = localStorage.getItem('lang')
  if (savedLang && ['zh', 'en'].includes(savedLang)) {
    locale.value = savedLang
  }
}

// 语言变化事件处理
const handleLanguageChange = (event) => {
  const { language } = event.detail
  // 强制重新渲染组件以更新语言
  animationKey.value++
}

// 页面加载时初始化数据
onMounted(async () => {
  // 初始化语言设置
  initLanguage()
  
  // 监听语言变化事件
  window.addEventListener('languageChanged', handleLanguageChange)
  
  // 先加载国家列表
  await loadCountries()
  // 再并行加载其他数据
  await Promise.all([
    loadFilterOptions(),
    loadAllTalents()
  ])
  // 检查已申请状态
  await checkAppliedStatus()
})

// 组件卸载时清理事件监听器
onUnmounted(() => {
  window.removeEventListener('languageChanged', handleLanguageChange)
})

// 加载筛选选项
const loadFilterOptions = async () => {
  try {
    const response = await talentApi.getFilterOptions()
    if (response.code === 200) {
      // 保留现有的nationalities，只更新其他筛选选项
      const currentNationalities = filterOptions.value.nationalities
      filterOptions.value = response.data
      filterOptions.value.nationalities = currentNationalities
    } else {
      ElMessage.error(t('enterpriseTalentSearch.getFilterOptionsFailed'))
    }
  } catch (error) {
    ElMessage.error(t('enterpriseTalentSearch.getFilterOptionsFailed'))
  }
}

// 加载国家列表
const loadCountries = async () => {
  try {
    const response = await talentApi.getCountries()
    
    // 支持两种响应格式：code为'SUCCESS'或200
    if (response.code === 'SUCCESS' || response.code === 200) {
      // 处理国家列表数据，中国(ID:45)优先显示
      const countries = response.data || []
      
      // 查找中国记录
      const chinaCountry = countries.find(country => country.value === 45)
      
      if (chinaCountry) {
        // 过滤出除中国外的其他国家
        const otherCountries = countries.filter(country => country.value !== 45)
        // 将中国放在第一位，其他国家按原有顺序排列
        filterOptions.value.nationalities = [chinaCountry.label, ...otherCountries.map(country => country.label)]
      } else {
        // 如果没有找到中国，直接使用label字段
        filterOptions.value.nationalities = countries.map(country => country.label)
      }
    } else {
      ElMessage.error(`获取国家列表失败: ${response.message || '未知错误'}`)
    }
  } catch (error) {
    ElMessage.error('获取国家列表失败，请检查网络连接')
  }
}

// 加载所有人才（支持分页）
const loadAllTalents = async (page = 1) => {
  loading.value = true
  try {
    const response = await talentApi.getAllTalents(page, pageSize.value)
    if (response.code === 200) {
      talents.value = response.data || []
      totalCount.value = response.total || 0
      currentPage.value = response.page || 1
      pageSize.value = response.size || 10
      totalPages.value = response.totalPages || 0
      hasNext.value = response.hasNext || false
      hasPrevious.value = response.hasPrevious || false
    } else {
      ElMessage.error(response.message || '获取人才列表失败')
    }
  } catch (error) {
    ElMessage.error('获取人才列表失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 搜索方法
const search = async () => {
  if (!searchQuery.value.trim()) {
    currentPage.value = 1
    await loadAllTalents(1)
    return
  }
  
  loading.value = true
  try {
    const response = await talentApi.searchTalents(searchQuery.value.trim(), currentPage.value, pageSize.value)
    
    if (response.code === 200) {
      talents.value = response.data || []
      totalCount.value = response.total || 0
      currentPage.value = response.page || 1
      pageSize.value = response.size || 10
      totalPages.value = response.totalPages || 0
      hasNext.value = response.hasNext || false
      hasPrevious.value = response.hasPrevious || false
    } else {
      ElMessage.error(response.message || t('enterpriseTalentSearch.searchFailed'))
    }
  } catch (error) {
          ElMessage.error(t('enterpriseTalentSearch.searchNetworkError'))
  } finally {
    loading.value = false
  }
}

// 申请撮合
const requestMatch = async (talent) => {
  try {
    // 检查是否已经申请过
    if (talent.hasApplied) {
      ElMessage.warning('您已经对该人才发起过撮合请求，不允许重复申请')
      return
    }
    
    // 显示确认对话框
    const confirmed = await ElMessageBox.confirm(
      `确定要申请撮合 ${talent.fullName} 吗？\n\n注意：一旦发起撮合请求，无论状态如何都不能再次申请。`,
      '申请撮合确认',
      {
        confirmButtonText: '确定申请',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
    )
    
    if (confirmed) {
      // 调用真实API发送请求到数据库
      const response = await talentApi.requestMatch(talent.studentId)
      
      if (response.code === 200) {
        ElMessage.success('撮合请求提交成功，等待平台处理')
        // 更新人才状态，标记为已申请
        talent.hasApplied = true
        talent.requestStatus = 'submitted'
        talent.statusDisplay = '已提交'
        
        // 保存到本地存储（实际项目中应该由后端管理）
        const appliedTalents = JSON.parse(localStorage.getItem('appliedTalents') || '[]')
        const existingIndex = appliedTalents.findIndex(applied => applied.studentId === talent.studentId)
        
        if (existingIndex === -1) {
          appliedTalents.push({
            studentId: talent.studentId,
            status: 'submitted',
            statusDisplay: '已提交',
            requestTime: new Date().toISOString()
          })
        } else {
          appliedTalents[existingIndex] = {
            ...appliedTalents[existingIndex],
            status: 'submitted',
            statusDisplay: '已提交',
            requestTime: new Date().toISOString()
          }
        }
        
        localStorage.setItem('appliedTalents', JSON.stringify(appliedTalents))
      } else {
        // 处理各种错误情况
        switch (response.code) {
          case 400:
            if (response.message.includes('重复申请')) {
              ElMessage.error(response.message)
              // 如果是重复申请，也标记为已申请
              talent.hasApplied = true
              
              // 从错误信息中提取状态
              const statusMatch = response.message.match(/状态：(.+?)/)
              if (statusMatch) {
                talent.statusDisplay = statusMatch[1]
                // 保存到本地存储
                const appliedTalents = JSON.parse(localStorage.getItem('appliedTalents') || '[]')
                const existingIndex = appliedTalents.findIndex(applied => applied.studentId === talent.studentId)
                
                if (existingIndex === -1) {
                  appliedTalents.push({
                    studentId: talent.studentId,
                    status: 'submitted',
                    statusDisplay: statusMatch[1],
                    requestTime: new Date().toISOString()
                  })
                } else {
                  appliedTalents[existingIndex] = {
                    ...appliedTalents[existingIndex],
                    statusDisplay: statusMatch[1]
                  }
                }
                
                localStorage.setItem('appliedTalents', JSON.stringify(appliedTalents))
              }
            } else {
              ElMessage.error(response.message || '请求参数错误')
            }
            break
          case 403:
            ElMessage.error('权限不足，只有企业用户可以请求撮合')
            break
          case 404:
            if (response.message.includes('学生不存在')) {
              ElMessage.error(t('enterpriseTalentSearch.studentNotExists'))
            } else if (response.message.includes('企业信息')) {
              ElMessage.error('企业信息不完整，请先完善企业信息')
            } else {
              ElMessage.error(response.message || '资源不存在')
            }
            break
          case 500:
            ElMessage.error('撮合请求提交失败，请稍后重试')
            break
          default:
            ElMessage.error(response.message || '申请撮合失败')
        }
      }
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消操作，不显示错误信息
      return
    }
    ElMessage.error('申请撮合失败，请检查网络连接')
  }
}

// 查看人才详情
const viewTalentDetail = async (talent) => {
  try {
    const response = await talentApi.getTalentDetail(talent.studentId)
    if (response.code === 200) {
      showTalentDetailDialog(response.data)
    } else {
      ElMessage.error(response.message || '获取人才详情失败')
    }
  } catch (error) {
    ElMessage.error('获取人才详情失败，请检查网络连接')
  }
}

// 显示人才详情弹窗
const showTalentDetailDialog = (talentDetail) => {
  currentTalentDetail.value = talentDetail
  talentDetailVisible.value = true
}

// 筛选处理
const selectFilter = async (type, value) => {
  
  // 单选类型：国籍、学历
  const singleChoiceTypes = ['nationality', 'education']
  
  if (value === '全部') {
    // 如果点击"全部"，清空该类型的所有选择
    selectedFilters.value[type] = []
  } else {
    if (singleChoiceTypes.includes(type)) {
      // 单选逻辑：直接替换当前选择
      if (selectedFilters.value[type].includes(value)) {
        // 如果已选中，则取消选择（回到全部）
        selectedFilters.value[type] = []
      } else {
        // 如果未选中，则选中（替换之前的选择）
        selectedFilters.value[type] = [value]
      }
    } else {
      // 多选逻辑：专业、语言、技能
      if (selectedFilters.value[type].includes(value)) {
    // 如果当前选项已选中，则取消选中
      selectedFilters.value[type] = selectedFilters.value[type].filter(item => item !== value)
    } else {
      // 如果当前选项未选中，则选中
      selectedFilters.value[type].push(value)
    }
    }
  }
  
  // 触发筛选
  await applyFilters()
}

// 应用筛选
const applyFilters = async () => {
  // 构建筛选参数
  const filters = {}
  
  // 单选类型：国籍、学历
  const singleChoiceTypes = ['nationality', 'education']
  
  Object.keys(selectedFilters.value).forEach(type => {
    if (selectedFilters.value[type].length > 0) {
      // 根据后端接口参数名映射
      const paramMap = {
        nationality: 'nationality',
        major: 'major', 
        education: 'degree',
        language: 'language',
        skill: 'skill'
      }
      
      if (singleChoiceTypes.includes(type)) {
        // 单选类型：只取第一个值
        filters[paramMap[type]] = selectedFilters.value[type][0]
      } else {
        // 多选类型：目前后端只支持单值，所以也只取第一个值
        // 后续可以扩展为支持多值筛选
      filters[paramMap[type]] = selectedFilters.value[type][0]
      }
    }
  })
  
  // 如果没有筛选条件，加载所有人才
  if (Object.keys(filters).length === 0) {
    currentPage.value = 1
    await loadAllTalents(1)
    return
  }
  
  loading.value = true
  try {
    // 添加分页参数到筛选请求中
    const requestParams = {
      ...filters,
      page: currentPage.value,
      size: pageSize.value
    }
    const response = await talentApi.filterTalents(requestParams)
    if (response.code === 200) {
      talents.value = response.data || []
      totalCount.value = response.total || 0
      currentPage.value = response.page || 1
      pageSize.value = response.size || 10
      totalPages.value = response.totalPages || 0
      hasNext.value = response.hasNext || false
      hasPrevious.value = response.hasPrevious || false
    } else {
      ElMessage.error(response.message || t('enterpriseTalentSearch.filterFailed'))
    }
  } catch (error) {
          ElMessage.error(t('enterpriseTalentSearch.filterNetworkError'))
  } finally {
    loading.value = false
  }
}

// 移除单个筛选条件
const removeFilter = async (type, value) => {
  selectedFilters.value[type] = selectedFilters.value[type].filter(item => item !== value)
  await applyFilters()
}

// 清除所有筛选条件
const clearAllFilters = async () => {
  Object.keys(selectedFilters.value).forEach(type => {
    selectedFilters.value[type] = []
  })
  
  currentPage.value = 1
  await loadAllTalents(1)
}

// 显示更多国家选择弹窗
const showMoreNationalities = () => {
  moreNationalitiesVisible.value = true
}

// 从更多国家中选择一个国家
const selectFromMoreNationalities = (nationality) => {
  selectedFilters.value.nationality = [nationality]
  moreNationalitiesVisible.value = false
  applyFilters()
}

// 切换更多筛选条件展开/收起
const toggleMoreFilters = () => {
  showMoreFilters.value = !showMoreFilters.value
}


// 获取筛选条件类型名称
const getFilterTypeName = (type) => {
  switch (type) {
    case 'nationality':
      return t('enterpriseTalentSearch.nationality')
    case 'major':
      return t('enterpriseTalentSearch.major')
    case 'education':
      return t('enterpriseTalentSearch.education')
    case 'language':
      return t('enterpriseTalentSearch.language')
    case 'skill':
      return t('enterpriseTalentSearch.skill')
    default:
      return type.charAt(0).toUpperCase() + type.slice(1)
  }
}

// 分页处理函数
const handleCurrentChange = async (page) => {
  currentPage.value = page
  await loadAllTalents(page)
}

const handleSizeChange = async (size) => {
  pageSize.value = size
  currentPage.value = 1
  await loadAllTalents(1)
}

// 日期格式化
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}

// 获取简历状态类型
const getResumeStatusType = (status) => {
  switch (status) {
    case 'approved': return 'success'
    case 'pending': return 'warning'
    case 'rejected': return 'danger'
    case 'incomplete': return 'info'
    default: return 'info'
  }
}

// 获取简历状态文本
const getResumeStatusText = (status) => {
  switch (status) {
    case 'approved': return t('enterpriseTalentSearch.approved')
    case 'pending': return t('enterpriseTalentSearch.pending')
    case 'rejected': return t('enterpriseTalentSearch.rejected')
    case 'incomplete': return t('enterpriseTalentSearch.incomplete')
    default: return t('enterpriseTalentSearch.unknown')
  }
}


</script>

<style scoped>
.talent-search-page {
  min-height: 100vh;
  background: #f8f9fa;
}

/* 顶部导航栏 */
.page-header {
  background: #9ba1a7;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  padding: 16px 0;
}

.header-container {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  position: relative;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
}

.logo-icon {
  display: flex;
  align-items: center;
}

.logo-image {
  width: 32px;
  height: 32px;
  object-fit: contain;
}

.logo-title {
  font-size: 1.4rem;
  font-weight: 600;
  color: white;
  margin: 0;
}

.navigation {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
  gap: 40px;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.nav-link {
  color: white;
  text-decoration: none;
  font-weight: 500;
  font-size: 15px;
  transition: color 0.2s ease;
  position: relative;
  padding: 8px 0;
}

.nav-link:hover {
  color: #e9ecef;
}

.nav-link.active {
  color: #ffffff;
  font-weight: 600;
}

.nav-link.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: #ffffff;
}

.nav-icons {
  display: flex;
  align-items: center;
  gap: 16px;
}

.icon-item {
  color: white;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: background-color 0.2s ease;
}

.icon-item:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

/* 搜索区域 */
.search-section {
  background: white;
  padding: 30px 0;
  border-bottom: 1px solid #e8e8e8;
}

.search-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.search-bar {
  display: flex;
  gap: 15px;
  margin-bottom: 30px;
  justify-content: center;
  align-items: center;
}

.search-input {
  width: 50%;
  max-width: 400px;
}

.search-btn {
  min-width: 100px;
}



/* 筛选器 */
.filter-section {
  margin-top: 20px;
  background: #fff;
  padding: 20px;
}

.filter-row {
  display: flex;
  align-items: flex-start;
  gap: 24px;
  padding: 14px 0;
  position: relative;
}
/* 行底部分隔线 */
.filter-row::after {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 1px;
  background: #eaeaea;
}
.filter-row:last-child::after {
  display: none;
}

.filter-label {
  font-size: 15px;
  font-weight: 700;
  color: #111;
  min-width: 88px; /* 与示例保持一致 */
  padding-top: 4px;
}

.filter-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 16px 20px;
  flex: 1;
  align-items: center;
}

/* 纯文字标签样式 */
.filter-tag {
  /* 移除所有按钮样式 */
  background: transparent;
  border: none;
  border-radius: 0;
  padding: 0;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  transition: color 0.2s ease;
  text-decoration: none;
  white-space: nowrap;
  user-select: none;
}

/* 悬停状态：只改变文字颜色 */
.filter-tag:hover {
  color: #0066cc;
}

/* 选中状态：加粗文字，改变颜色 */
.filter-tag.active {
  color: #0066cc;
  font-weight: 600;
}

/* 单选样式：类似单选按钮 */
.single-choice .filter-tag.active {
  color: #0066cc;
  font-weight: 600;
  position: relative;
}

.single-choice .filter-tag.active::before {
  content: "●";
  margin-right: 4px;
  color: #0066cc;
}

/* 多选样式：类似复选框 */
.multi-choice .filter-tag.active {
  color: #0066cc;
  font-weight: 600;
  position: relative;
}

.multi-choice .filter-tag.active::before {
  content: "✓";
  margin-right: 4px;
  color: #0066cc;
}

/* 取消首个“全部”标签默认蓝底样式 */
/* 删除或注释掉此前的 .filter-tag:first-child 规则 */
.filter-tag:first-child {
  background: transparent;
  border: none;
  color: #0066cc;
  font-weight: 600;
}

/* 显示更多按钮样式 */
.show-more-filters {
  text-align: center;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #e8e8e8;
}

.show-more-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  color: #0066cc;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: color 0.2s ease;
}

.show-more-btn:hover {
  color: #0056b3;
}

.arrow-icon {
  transition: transform 0.3s ease;
}

.arrow-icon.rotated {
  transform: rotate(180deg);
}

/* 可展开的筛选条件样式 */
.expandable-filters {
  margin-top: 0;
  padding-top: 0;
}

/* 筛选条件展开/收起动画 */
.filter-expand-enter-active,
.filter-expand-leave-active {
  transition: all 0.3s ease;
  max-height: 500px;
  overflow: hidden;
}

.filter-expand-enter-from,
.filter-expand-leave-to {
  max-height: 0;
  opacity: 0;
  transform: translateY(-10px);
}

.filter-expand-enter-to,
.filter-expand-leave-from {
  max-height: 500px;
  opacity: 1;
  transform: translateY(0);
}

@media (max-width: 768px) {
  .filter-row {
    flex-direction: column;
    align-items: flex-start;
  }
  .filter-label {
    padding-top: 0;
    margin-bottom: 6px;
  }
  
  .talents-grid {
    grid-template-columns: 1fr;
  }
}



/* 人才卡片区域 */
.talents-section {
  padding: 40px 0;
}

.talents-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.talents-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 20px;
}

.talent-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.talent-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.talent-header {
  margin-bottom: 15px;
}

.talent-info {
  flex: 1;
}

.talent-name-row {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 5px;
}

.talent-name {
  font-size: 1.1rem;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.status-tag {
  flex-shrink: 0;
}

.talent-location,
.talent-major {
  font-size: 0.9rem;
  color: #666;
  margin: 0 0 3px 0;
}

.talent-details {
  margin-bottom: 15px;
}

.detail-item {
  margin-bottom: 8px;
}

.detail-label {
  font-weight: 500;
  color: #333;
  margin-right: 5px;
}

.detail-value {
  color: #666;
  font-size: 0.9rem;
}

/* 人才详情弹窗样式 - 简历格式 */
.talent-detail-content {
  max-height: 80vh;
  overflow-y: auto;
  padding: 20px;
  background: #fff;
}

/* 简历头部 - 姓名 */
.resume-header {
  text-align: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
}

.resume-name {
  font-size: 28px;
  font-weight: 700;
  color: #000;
  margin: 0;
  letter-spacing: 2px;
}

/* 基本信息区域 */
.basic-info-section {
  text-align: center;
  margin-bottom: 30px;
  padding: 15px 0;
}

.basic-info-line {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.basic-info-line:last-child {
  margin-bottom: 0;
}

.basic-info-line span {
  position: relative;
}

.basic-info-line span:not(:last-child)::after {
  content: "|";
  margin-left: 8px;
  color: #666;
  font-weight: normal;
}

/* 简历各个部分 */
.resume-section {
  margin-bottom: 25px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #000;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ddd;
  text-align: left;
}

.section-content {
  padding-left: 0;
  text-align: left;
  overflow: visible !important;
  max-height: none !important;
  height: auto !important;
}



/* 教育背景样式 */
.education-item {
  padding: 0;
}

.education-info {
  display: flex;
  gap: 15px;
  align-items: center;
  text-align: left;
}

.education-degree {
  font-weight: normal;
  color: #666;
  font-size: 14px;
}

.education-major {
  color: #666;
  font-size: 14px;
}

/* 文本内容样式 */
.text-content {
  line-height: 1.6;
  color: #666;
  font-size: 14px;
  padding: 10px 0;
  text-align: left;
}

/* 简历内容样式 */
.resume-content {
  padding: 0;
  overflow: visible !important;
  max-height: none !important;
  height: auto !important;
}

/* 只移除滚动和高度限制，保留其他富文本样式 */
.resume-content *,
.resume-content div,
.resume-content p,
.resume-content span {
  max-height: none !important;
  overflow: visible !important;
}

/* 简历状态样式 */
.resume-status {
  display: flex;
  align-items: center;
  gap: 15px;
  text-align: left;
}

.resume-status .el-tag {
  background: #fff !important;
  border: 1px solid #666 !important;
  color: #666 !important;
}

.update-time {
  color: #666;
  font-size: 13px;
}

.resume-content {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 6px;
  line-height: 1.6;
  color: #606266;
  max-height: 200px;
  overflow-y: auto;
}

.resume-status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.talent-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
}

/* 加载状态 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

/* 结果统计 */
.result-stats {
  margin-bottom: 20px;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.result-stats p {
  margin: 0;
  color: #666;
  font-size: 0.9rem;
}

/* 空状态 */
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  color: #999;
  font-size: 1rem;
}

/* 分页容器 */
.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 30px;
  padding: 20px 0;
}

/* 人才信息样式调整 */
.talent-nationality {
  font-size: 0.9rem;
  color: #666;
  margin: 0 0 3px 0;
}

.talent-education {
  font-size: 0.9rem;
  color: #666;
  margin: 0 0 3px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .navigation {
    gap: 15px;
  }
  
  .search-bar {
    flex-direction: column;
  }
  
  .filter-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .filter-label {
    min-width: auto;
    padding-top: 0;
  }
  
  .filter-tags {
    gap: 6px;
  }
  
  .filter-tag {
    padding: 5px 10px;
    font-size: 12px;
  }
  
  .talents-grid {
    grid-template-columns: 1fr;
  }
  
  /* 简历详情响应式 */
  .talent-detail-content {
    padding: 15px;
  }
  
  .resume-name {
    font-size: 24px;
    letter-spacing: 1px;
  }
  
  .basic-info-section {
    padding: 12px 0;
  }
  
  .basic-info-line {
    flex-direction: column;
    gap: 4px;
    font-size: 13px;
    color: #666;
  }
  
  .basic-info-line span:not(:last-child)::after {
    display: none;
  }
  
  .section-title {
    font-size: 16px;
  }
  
  .education-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
  
  .education-degree {
    font-size: 15px;
  }
  
  .education-major {
    font-size: 13px;
  }
  
  .text-content {
    font-size: 13px;
    padding: 8px 0;
    color: #666;
  }
  
  .resume-content {
    padding: 12px;
    font-size: 13px;
  }
  
  .resume-status {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}

/* 更小屏幕的响应式设计 */
@media (max-width: 480px) {
  .talent-detail-content {
    padding: 10px;
  }
  
  .resume-name {
    font-size: 20px;
    letter-spacing: 0.5px;
  }
  
  .basic-info-section {
    padding: 10px 0;
    margin-bottom: 20px;
  }
  
  .basic-info-line {
    font-size: 12px;
    color: #666;
  }
  
  .section-title {
    font-size: 15px;
  }
  
  .education-item {
    padding: 0;
  }
  
  .education-degree {
    font-size: 14px;
  }
  
  .education-major {
    font-size: 12px;
  }
  
  .text-content {
    font-size: 12px;
    padding: 6px 0;
    color: #666;
  }
  
  .resume-content {
    padding: 0;
    font-size: 12px;
    line-height: 1.6;
    color: #666;
  }
  
  .update-time {
    font-size: 12px;
  }
}

/* 其他国家选择弹窗样式 */
.more-nationalities-content {
  max-height: 400px;
  overflow-y: auto;
}

.nationalities-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 10px;
  padding: 10px 0;
}

.nationality-item {
  padding: 8px 12px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  cursor: pointer;
  text-align: center;
  transition: all 0.3s ease;
  font-size: 14px;
}

.nationality-item:hover {
  background: #e9ecef;
  border-color: #6c757d;
  transform: translateY(-1px);
}

.nationality-item:active {
  transform: translateY(0);
  background: #dee2e6;
}
</style>